package com.mqtt.demo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.FragmentActivity
import com.google.protobuf.ByteString
import com.tikin.message.proto.MsgBody
import com.tikin.message.proto.MsgHeader
import com.tikin.message.proto.TransmitMessage
import com.tikin.mqtt.MqttManagerOption
import com.tikin.mqtt.service.MqttManager
import com.tikinmedia.oms.*
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity :FragmentActivity() {

    private var handle :Handler? = null

    private var opt = MqttManagerOption(
        uri = "tcp://120.92.85.217:1883",
        userName = "tymedia",
        password = "tymedia",
        clientId = "_88EJdvCGkyhhJ9P5TvXpA==",
        topicLoc = "topic_tms_share",
        topic = arrayOf(
            "subscribe.device._88EJdvCGkyhhJ9P5TvXpA==.BEIJING",
            "subscribe.device.*.BEIJING",
            "subscribe.#.device.BEIJING"
        ),
        qos = intArrayOf(1, 1, 1)
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val callback = Handler.Callback { msg ->
            if (msg.what == 100) {
                runOnUiThread {
                    val manager = MqttManager(this@MainActivity.applicationContext, opt,handle!!)
                    manager.initClient(getWill())
                }
            }
            true
        }
        handle = Handler(Looper.getMainLooper(), callback)


        btn.setOnClickListener {
            val manager = MqttManager(this@MainActivity.applicationContext, opt,handle!!)
            manager.initClient(getWill())
        }
    }

    private fun getWill(): TransmitMessage.Builder{
        val h1 = MsgHeader.Header.newBuilder().setMsgAction(MsgHeader.Header.ActionType.BURIED_POINT).setMsgType(2)
        val b1 = MsgBody.Body.newBuilder().setAppKey(ByteString.copyFrom(opt.clientId, "UTF-8"))
        val will = TransmitMessage.newBuilder().setHeader(h1).setBody(b1)
        return will
    }

}